<?php
/**
 * Created By PhpStorm.
 * User: RenJianHong
 * Date: 2021-08-03 14:32
 */

namespace Modules\Order\Entities;
use Modules\Order\Entities\OrderDetail;
use Modules\Order\Entities\Order;
use Illuminate\Support\Facades\DB;

class Goods extends BaseModel
{
    protected $table = "goods";
    protected $guarded = [];

    /**
     * 根据规格获取商品的库存及规格价格信息
     * @param array $attr_id_list 规格id列表 eg. [1,4,9]
     * @return array|null eg.
     */
    public function getAttrInfo($attr_id_list,$goods)
    {
        sort($attr_id_list);
        $attr_rows = json_decode($goods->attr, true);
        if (empty($attr_rows)) {
            return null;
        }

        foreach ($attr_rows as $i => $attr_row) {
            $key = [];
            foreach ($attr_row['attr_list'] as $j => $attr) {
                $key[] = $attr['attr_id'];
            }
            sort($key);
            if (!array_diff($attr_id_list, $key)) {
                if (!$attr_rows[$i]['price']) {
                    $attr_rows[$i]['price'] = $goods->price;
                }
                return $attr_rows[$i];
            }
        }
        return null;
    }

    /**
     * 获取商品积分抵扣信息
     * @param $goods // 商品对象
     * @param $price // 金额
     * @param int $num 购买数量
     * @param array $integral 积分总使用信息  "forehead" => 0,  // 可以抵扣金额   "forehead_integral" => 0, // 使用积分数量,  "scale" => 0, // N积分抵扣1元
     * @return mixed
     */
    public function getIntegralInfo($goods, $price, int $num, array $integral)
    {
        $data = [
            "forehead" => 0,
            "forehead_integral" => 0,
        ];
        return $data;
        if(isset($integral['scale']) && $integral["scale"] > 0) {  // N积分抵扣1元
            $goodsInfoIntegral = json_decode($goods->integral, true);
            if(isset($goodsInfoIntegral['forehead'])){
                if(is_numeric($goodsInfoIntegral['forehead'])){
                    if($goodsInfoIntegral['forehead'] > 0);
                }
            }

            $goodsInfoIntegral["forehead"] = "3.2";
            $goodsInfoIntegral["a"] = is_numeric("3.2123");
            $goodsInfoIntegral["b"] = is_numeric("3%");
            $goodsInfoIntegral["c"] = is_numeric("13%");
            $data["gg"] = $goodsInfoIntegral;
            if(isset($goodsInfoIntegral['forehead']) && $goodsInfoIntegral['forehead'] > 0){
                $data["forehead"] = $goodsInfoIntegral['forehead'];
            }

            //"give": "8",
            //									"forehead": "3",
            //									"more": "1"
        }

        if($integral["scale"] > 0){  // N积分抵扣1元
//            $goodsInfoIntegral = json_decode($goods->integral, true);
//            $give = $goodsInfoIntegral["give"] ?? "";  // 购买赠送积分基数：空或者0不赠送，带%为 总金额 * N%, 不带%为 N
//            if(is_numeric($give)){
//
//            }

//            $forehead = $goodsInfoIntegral["forehead"] ?? ""; // 商品积分最大抵扣金额：空或者0不能抵扣，带%为 金额 * N%, 不带%为 N
//            $more = $goodsInfoIntegral["more"] ?? 0; // 是否累计抵扣金额：空或者0不累计，1 = 数量 * forehead

        }



        return $data;
    }

    /**
     * @param $user User
     * @param $goods_id
     * @return false|null|string
     * 查找指定用户指定商品购买数量
     */
    public static function getBuyNum($user,$goods_id)
    {
        
        $where = [
            ['order_detail.goods_id','=',$goods_id],
            ['order.user_id','=',$user->id],
            ['order.order_status','=',1],
            ['order.is_delete','=',0]
        ];
        $goodsNum = OrderDetail::where($where)
            ->leftJoin('order', 'order_detail.order_id', '=', 'order.id')
            ->selectRaw('SUM(goods_num) as num')->value('num');
            
        return $goodsNum;
    }

    /**
     * 单品满件包邮 单品满额包邮
     */
    public static function cutFull($goodsList)
    {
        // 将商品ID相同的商品合并
        $newGoodsList = [];
        foreach ($goodsList as $row) {
            if (isset($newGoodsList[$row['goods_id']])) {
                $newGoodsList[$row['goods_id']]['num'] += $row['num'];
                $newGoodsList[$row['goods_id']]['weight'] += $row['weight'] * $row['num'];
                $newGoodsList[$row['goods_id']]['price'] += $row['price'];
            } else {
                $row['weight'] = $row['weight'] * $row['num'];
                $newGoodsList[$row['goods_id']] = $row;
            }
        }
        $resGoodsList = [];
        foreach ($newGoodsList as $val) {
            $full_cut['pieces'] = $val['num_full'];
            $full_cut['forehead'] = $val['price_full'];
            $val['full_cut'] = json_encode($full_cut);
            
            if ($val['full_cut']) {
                $full_cut = json_decode($val['full_cut'], true);
            } else {
                $full_cut = [
                    'pieces' => 0,
                    'forehead' => 0,
                ];
            }
            $val['full_cut'] = $full_cut;
            if ((empty($full_cut['pieces']) || $val['num'] < ($full_cut['pieces'] ?: 0)) && (empty($full_cut['forehead']) || $val['price'] < ($full_cut['forehead'] ?: 0))) {
                $resGoodsList[] = $val;
            }
        }
        
        return $resGoodsList;
    }

    /**
     * 库存增加操作
     */
    public function numAdd($attr_id_list, $num,$_goods)
    {
        sort($attr_id_list);
        $attr_group_list = json_decode($_goods->attr);
        $add_attr_num = false;
        foreach ($attr_group_list as $i => $attr_group) {
            $group_attr_id_list = [];
            foreach ($attr_group->attr_list as $attr) {
                array_push($group_attr_id_list, $attr->attr_id);
            }
            sort($group_attr_id_list);
            if (!array_diff($attr_id_list, $group_attr_id_list)) {
                $attr_group_list[$i]->num = intval($attr_group_list[$i]->num) + $num;
                $add_attr_num = true;
                break;
            }
        }
        if (!$add_attr_num) {
            return false;
        }
        $this->attr = json_encode($attr_group_list, JSON_UNESCAPED_UNICODE);
        $this->save();
        return true;
    }

    /**
     * 库存减少操作
     * @param array $attr_id_list eg. [1,4,2]
     */
    public function numSub($attr_id_list, $num,$_goods)
    {
        sort($attr_id_list);
        $attr_group_list = json_decode($_goods->attr);;
        
        $sub_attr_num = false;
        foreach ($attr_group_list as $i => $attr_group) {
            $group_attr_id_list = [];
            
            foreach ($attr_group->attr_list as $attr) {
                
                array_push($group_attr_id_list, $attr->attr_id);
            }
            sort($group_attr_id_list);
            if (!array_diff($attr_id_list, $group_attr_id_list)) {
                if ($num > intval($attr_group_list[$i]->num)) {
                    return false;
                }
                $attr_group_list[$i]->num = intval($attr_group_list[$i]->num) - $num;
                $sub_attr_num = true;
                break;
            }
            
        }
        if (!$sub_attr_num) {
            return false;
        }
        
        $this->attr = json_encode($attr_group_list, JSON_UNESCAPED_UNICODE);
        $this->save();
        return true;
    }
    
}